import requests
import numpy as np
import os
import time
import dashscope


def call_llm_model(prompt):
    url = "http://localhost:8000/generate/"
    payload = {"text": prompt}
    response = requests.post(url, json=payload)

    data = response.json()

    if "response" in data:
        return data["response"]
    
    else:
        return None


def call_embedding_model(query):
    url = "http://localhost:8000/embedding/"
    payload = {"text": query}
    response = requests.post(url, json=payload)

    data = response.json()
    if "embedding" in data:
        return np.array(data["embedding"], dtype=np.float32)

    else:
        return None


# result = call_embedding_model("介绍下大模型有哪些种类")
# print(result)
# print(len(result[0]))


def get_embedding(text):
    resp = dashscope.TextEmbedding.call(
        api_key="sk-f061d20155e6494fa7737ce6e6aaf5af",
        model=dashscope.TextEmbedding.Models.text_embedding_v3,
        input= text,
        dimension=1024,
        output_type="dense&sparse"
    )

    try:
        embedding = resp['output']['embeddings'][0]['embedding']
        return embedding
    except:
        return None


def get_image_infos(image_path, prompt):
    start_time = time.time()
    messages = [
        {
            "role": "user",
            "content": [
                {"image": image_path},
                {"text": prompt}
            ]
        }
    ]

    response = dashscope.MultiModalConversation.call(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key="sk-f061d20155e6494fa7737ce6e6aaf5af",
        model='qwen-vl-max', # 此处以qwen-vl-max为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        messages=messages
        )

    # print(response)
    end_time = time.time()
    cost_time = end_time - start_time

    try:
        content = response['output']['choices'][0]['message']['content'][0]['text']
        tokens = response['usage']['total_tokens']
        return content, tokens, cost_time
    except:
        return None, 0, cost_time